﻿using Microsoft.Win32;
using System;
using System.Data;
using System.Data.Odbc;

namespace Platform.DB
{
    public class OdbcFactory : IDbFactory
    {
        #region 构造

        public OdbcFactory()
        {
            try
            {
                RegistryKey localMachine = Registry.LocalMachine;
                RegistryKey registryKey = localMachine.OpenSubKey("SOFTWARE").OpenSubKey("ODBC").OpenSubKey("ODBCINST.INI");
                string[] subKeyNames = registryKey.GetSubKeyNames();
                foreach (string text in subKeyNames)
                {
                    if (text.StartsWith("MySQL ODBC"))
                    {
                        RegistryKey registryKey2 = registryKey.OpenSubKey(text, true);
                        registryKey2.SetValue("CPTimeout", "120");
                    }
                }
            }
            catch
            {
            }
            this._connectString = "DRIVER={MySQL ODBC 5.1 Driver};SERVER=localhost;OPTION=3;UID=root;PASSWORD=ndk;DATABASE=AFMT_DB;";
        }

        #endregion

        #region 字段属性

        private string _connectString;

        public string ConnectString
        {
            get
            {
                return this._connectString;
            }
            set { _connectString = value; }
        }

        #endregion

        #region IDbFactory实现

        public IDbConnection CreateConnection()
        {
            return new OdbcConnection(this._connectString);
        }

        public IDbConnection CreateConnection1(string dbname)
        {
            return new OdbcConnection($"server=localhost;user=root;port=3306;password=ndk;DATABASE={dbname};");
        }

        public IDbDataAdapter CreateDataAdapter()
        {
            return new OdbcDataAdapter();
        }

        public IDataParameter CreateDataParameter()
        {
            return new OdbcParameter();
        }

        public bool CreateDb(string dbName)
        {
            ConnectString = $"server=localhost;user=root;port=3306;password=ndk;DATABASE={dbName};";
            string text = this._connectString;
            int length = text.IndexOf("DATABASE", StringComparison.OrdinalIgnoreCase);
            text = text.Substring(0, length);
            IDbConnection dbConnection = null;
            try
            {
                dbConnection = new OdbcConnection(text);
                dbConnection.Open();
                string commandText = "CREATE DATABASE IF NOT EXISTS " + dbName + " DEFAULT CHARACTER SET utf8";
                IDbCommand dbCommand = dbConnection.CreateCommand();
                dbCommand.CommandText = commandText;
                dbCommand.ExecuteNonQuery();
            }
            finally
            {
                if (dbConnection != null)
                {
                    dbConnection.Close();
                }
            }
            return true;
        }

        #endregion

        #region 共有方法



        #endregion

    }
}
